package cn.itlaobing.web.fileter;

import cn.itlaobing.web.Constants;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xuaner on 2017/11/6.
 * 拦截除了login.jsp之外的所有的请求
 */
@WebFilter("/*")
public class LoginFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig)throws ServletException {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException,ServletException{
        HttpServletRequest req=null;
        HttpServletResponse res=null;
        if(request instanceof HttpServletRequest){
            req=(HttpServletRequest) request;
        }
        if(response instanceof HttpServletResponse){
            res=(HttpServletResponse) response;
        }
        //设置字符编码
        req.setCharacterEncoding("utf-8");
        String requestUrl=req.getRequestURI();
        if("/login.jsp".equals(requestUrl)||"/user/login".equals(requestUrl)||requestUrl.startsWith("/style")){
            chain.doFilter(req,res);//放行
        }else{
            //判断是否登录
            if(req.getSession().getAttribute(Constants.CURRENT_USER)==null){
                // /用户还没有登录，转到登录的页面
                req.getSession().setAttribute("msg","请登录后再操作！");
                res.sendRedirect(req.getContextPath()+"/login.jsp");
                return;
            }else{
                //已经登录，====放行
                chain.doFilter(req,res);
            }

        }
    }
    @Override
    public void destroy(){
    }
}
